// pages/store/store.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    storeDetail:{},
    carousels:[],
    view_top:0,
    view_height:0,
    like:false,
    premiumid:0,
    id: 0,
    address: [],
  },

  onReady: function () {
    const that = this;
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let t = this;
    t.setData({
      alert: t.selectComponent("#alert"),
      confirm: t.selectComponent("#confirm"),
      popup: t.selectComponent("#popup"),
    });
    t.api.interface.integralMallGetDetail({
      id:options.id,
    }).then(result=>{
      console.log(result.data.data,111111111111111111)
      if (result.data.data) {
        t.getSystemInfo();

        var storeDetail = result.data.data;
        var carousels = storeDetail.carousels;
        var carousels_new = [];
        for(var i=0;i<carousels.length;i++){
          if(carousels[i] != ''){
            carousels_new.push(carousels[i]);
          }
        }
        t.setData({
          id:options.id,
          storeDetail: storeDetail,
          carousels:carousels_new,
          like: result.data.data.collect,
        });

        if(options.address_id){
          t.api.interface.getCustomerAddress(options.address_id).then(res => {
            if(res.data.code == 200){
              let region = res.data.data.region;
              let arr_region = region.split(",");

              var address = {};
              address.userName = res.data.data.realname,
              address.telNumber = res.data.data.mobile,
              address.provinceName = arr_region[0];
              address.cityName = arr_region[1];
              address.countyName = arr_region[2];
              address.detailInfo = res.data.data.address;
              t.setData({
                address: address,
              });
              // 弹窗
              t.onConfirm(t);

            }
          });
        }
      }
    });

  },
  getSystemInfo() {
    let t = this;
    wx.getSystemInfo({
      success: res => {
        var w = res.windowWidth;
        var h = res.windowHeight;

        var view_top = h * 0.15;
        var view_height = h * 0.745;


        this.setData({
          winWidth:res.windowWidth,
          winHeight: res.windowHeight,
          view_top:view_top,
          view_height:view_height,

        });
      },
    })
  },
  onLikeTap(event) {
    let that = this
    that.setData({
      like: true,
    });
    this.api.interface.integralcollection({
      premiumid:event.currentTarget.dataset.id
    }).then(res=>{

    })
  },
  // 立即兑换
  onExchangeTap(event) {
    let that = this
    if (that.data.storeDetail.convertedNumber >= that.data.storeDetail.canExchangedNumber) {
      that.data.alert.show({
        content: that.data.storeDetail.errorMsg,
      });
      return false;
    }
    if ((that.data.storeDetail.discountPoint ? that.data.storeDetail.discountPoint : that.data.storeDetail.point) > that.data.storeDetail.usableTotal) {
      that.data.alert.show({
        content: '会员积分不足，兑换失败',
        closeButtonText: '了解更多会员积分获取途径',
        onClosed: function () {
          that.data.popup.show({});
        }
      });
      return false;
    }
    if (1 === that.data.storeDetail.errorCode) {
      that.data.alert.show({
        content: that.data.storeDetail.errorMsg,
      });
      return false;
    }

    if (that.data.storeDetail.premiumNormalType == 8 || that.data.storeDetail.premiumNormalType == 11) {
      // 好友试用福利 新客首单福利
      that.onConfirm(that);
    } else {

      switch (that.data.storeDetail.specNo) {
        case '0':
          wx.redirectTo({
            url: '../addresslist/addresslist?type=2&store_id='+that.data.id,
          });
          //that.onChooseAddress(that);
          break;
        case '1':
        case '2':
          var address = {};
          address.userName = '';
          address.telNumber = '';
          address.provinceName = '';
          address.cityName = '';
          address.countyName = '';
          address.detailInfo = '';
          that.setData({
            address: address,
          });
          that.onConfirm(that);
          break;
      }

    }



  },
  // 选择地址
  onChooseAddress(that) {
    // 获取到的收货人信息
    var receive = [];
    // 申请的试用产品编号
    receive['id'] = that.data.sampleId;
    // 授权或选择收货地址
    wx.getSetting({
      success(res) {
        if (res.authSetting['scope.address']) {
          wx.chooseAddress({
            success(res) {
              var address = {};
              address.userName = res.userName;
              address.telNumber = res.telNumber;
              address.provinceName = res.provinceName;
              address.cityName = res.cityName;
              address.countyName = res.countyName;
              address.detailInfo = res.detailInfo;
              that.setData({
                address: address,
              });
              // 弹窗
              that.onConfirm(that);
            }
          });
        }
        else {
          // 拒绝授权后跳到权限页面
          if (res.authSetting['scope.address'] == false) {
            wx.openSetting({});
          }
          else {
            wx.chooseAddress({
              success(res) {
                var address = {};
                address.userName = res.userName;
                address.telNumber = res.telNumber;
                address.provinceName = res.provinceName;
                address.cityName = res.cityName;
                address.countyName = res.countyName;
                address.detailInfo = res.detailInfo;
                that.setData({
                  address: address,
                });
                that.onConfirm(that);
              }
            });
          }
        }
      },
    });
  },
  // 确认弹窗的确认按钮
  onConfirm(that) {

    let needAddress = true;
    if (that.data.storeDetail.collectdataType == 'ADDRESS') {
      needAddress = true;
    } else {
      needAddress = false;
    }
    console.log(that.data.storeDetail.discountPoint+"======="+that.data.storeDetail.point);
    that.data.confirm.show({
      title: '您将使用' + (that.data.storeDetail.discountPoint ? that.data.storeDetail.discountPoint : that.data.storeDetail.point) + '活力值兑换',
      content: that.data.storeDetail.name,
      needAddress: needAddress,
      address: that.data.address.userName + '\n' + that.data.address.provinceName + that.data.address.cityName + that.data.address.countyName + that.data.address.detailInfo + '\n' + that.data.address.telNumber,
      onConfirm: function () {
        if (6 === that.data.storeDetail.premiumNormalType) { // 电子卡券
          wx.requestSubscribeMessage({
            tmplIds: ['DWLdFzujBYNzVrJLP7r6hjby74JbUdP3V_kWoetFH-s'],
            complete() {
              that.onSubmit();
            }
          });
        } else if (8 === that.data.storeDetail.premiumNormalType) { // 好友试用福利
          wx.requestSubscribeMessage({
            tmplIds: ['SBXHGqU8PjekWytRIwaGkPqnVRIrKI_dj0dyCmYVlt4'],
            complete() {
              that.onSubmit();
            }
          });
        } else if (11 === that.data.storeDetail.premiumNormalType) { // 新客首单福利
          wx.requestSubscribeMessage({
            tmplIds: ['PyhOvh8Yhxtgb788y5VzYGr0Evr833eRbl9nXHPRg1o'],
            complete() {
              that.onSubmit();
            }
          });
        }
        else {
          wx.requestSubscribeMessage({
            tmplIds: ['U5pzSnvAKGQRcTBu6-5wxCmw6n2B9AnGNPV6kpTSLkk'],
            complete() {
              that.api.interface.userSubscribeMessage({type: 3});
              that.onSubmit();
            }
          });
          // that.onSubmit();
        }
      }
    });
  },
  onSubmit() {
    // 显示载入
    let that = this
    console.log(that.data.storeDetail,'storeDetail- -- -- - -- >')
    wx.showLoading({});
    this.api.interface.integralexchange({
      premiumid: that.data.id,
      name: that.data.address.userName,
      mobile: that.data.address.telNumber,
      province: that.data.address.provinceName,
      city: that.data.address.cityName,
      area: that.data.address.countyName,
      address: that.data.address.detailInfo,
      code: that.data.storeDetail.code,
      specNo: that.data.storeDetail.specNo
    }).then(result=>{
      console.log(result,10987654321)
      if (1 === result.data.code) {
        wx.hideLoading()
        that.data.alert.show({
          content: result.data.message,
        });
        return false;
      }

      if (that.data.storeDetail.premiumNormalType == 8 || that.data.storeDetail.premiumNormalType == 11) {

        wx.hideLoading()

        if (that.data.storeDetail.premiumNormalType == 8) { // 好友试用福利
          this.setData({
            friendOntrialOrderId: result.data.data.orderId,
            alertType: '送你1份试用礼',
          })
        } else if (that.data.storeDetail.premiumNormalType == 11) { // 新客首单福利
          this.setData({
            alertType: '新客首单福利购买成功',
            alertCoupons: result.data.data.listRes
          })
        }

      } else {

        switch (that.data.storeDetail.specNo) {
          case '0':
            wx.redirectTo({
              url: '../storeResult/storeResult' + '?points=' + (that.data.storeDetail.discountPoint ? that.data.storeDetail.discountPoint : that.data.storeDetail.point) + '&name=' + that.data.storeDetail.name,
            });
            break;
          case '1':
            wx.redirectTo({
              url: '../storeResultCoupon/storeResultCoupon' + '?points=' + (that.data.storeDetail.discountPoint ? that.data.storeDetail.discountPoint : that.data.storeDetail.point) + '&name=' + that.data.storeDetail.name,
            });
            break;
          case '2':
            wx.redirectTo({
              url: '../storeResultHema/storeResultHema' + '?id=' + result.data.data.orderId + '&points=' + (that.data.storeDetail.discountPoint ? that.data.storeDetail.discountPoint : that.data.storeDetail.point) + '&name=' + that.data.storeDetail.name,
            });
            break;
        }

      }

    })
  },
  onShow() {
    const that = this;
  },

  onShareAppMessage() {

  },

})